package com.xiaoshuidi.cloud.module.system.service.ocr;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseRequest;
import com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.xiaoshuidi.cloud.module.system.service.ocr.dto.OcrDataDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.File;
import java.util.Objects;

/**
 * oos Service 实现类
 *
 * @author
 */
@Service
@Slf4j
public class OcrServiceImpl implements OcrService {

    @Resource
    private Client ocrClient;

    @Override
    public OcrDataDTO businessLicense(MultipartFile file, String url) {
        try {
            RecognizeBusinessLicenseRequest recognizeBusinessLicenseRequest = new RecognizeBusinessLicenseRequest();
            if (Objects.nonNull(file)){
                BufferedInputStream inputStream = FileUtil.getInputStream((File) file);
                recognizeBusinessLicenseRequest.setBody(inputStream);
            }else if (StringUtils.isNotBlank(url)){
                recognizeBusinessLicenseRequest.setUrl(url);
            }
            RuntimeOptions runtime = new RuntimeOptions();
            RecognizeBusinessLicenseResponse resp = ocrClient.recognizeBusinessLicenseWithOptions(recognizeBusinessLicenseRequest, runtime);
            if (Objects.nonNull(resp) && Objects.nonNull(resp.getBody()) && StringUtils.isNotBlank(resp.getBody().getData())){
                String data = resp.getBody().getData();
                JSONObject dataObj = JSONObject.parseObject(data);
                String dataObjDataStr = dataObj.getString("data");
                return JSONObject.parseObject(dataObjDataStr, OcrDataDTO.class);
            }
        } catch (Exception e) {
            log.error("OCR识别营业执照失败，异常信息：", e);
        }
        return null;
    }
}
